package cn.highedu.test;

public class Demo{
    public static void main(String[] args) {
        //Singleton s = new Singleton();
        Singleton s1 = Singleton.getInstance();
        Singleton s2 = Singleton.getInstance();
        Singleton s3 = Singleton.getInstance();
        System.out.println(s1 == s2);
        System.out.println(s1 == s3);

        Singleton2 s4 = Singleton2.getInstance();
        Singleton2 s5 = Singleton2.getInstance();
        System.out.println(s4==s5);
    }
}
/**
 * 单例模式, 饿汉式单例模式
 */
class Singleton {
    private static Singleton instance = new Singleton();
    private Singleton(){

    }
    public static Singleton getInstance() {
        return instance;
    }
}

/**
 * 懒汉式单例模式
 */
class Singleton2{
    private static Singleton2 instance;
    private Singleton2(){
    }

    public static synchronized Singleton2 getInstance() {
        if (instance == null){
            instance = new Singleton2();
        }
        return instance;
    }
}




